let config = {
  appid: '20180316000136493',
  key: 'w6I8U34fXTy2Y_JEp6Lj'
}

let cache = null


const translate = q => new Promise(async (resolve, reject) => {
  if (cache && cache.input === q) {
    return resolve(cache.output)
  }
  try {
    const from = 'auto'
    const to = 'zh'
    const appid = config.appid
    const salt = Date.now()
    const sign = MD5(appid + q + salt + config.key)
    const json = await axios.get('http://api.fanyi.baidu.com/api/trans/vip/translate', { params: { q: q, from, to, appid, salt, sign } })
    
    if (json.data.error_msg) {
      reject(Error(json.data.error_msg))
    } else {
      cache = { input: q, output: json.data.trans_result[0].dst }
      resolve(json.data.trans_result[0].dst)
    }
  } catch (e) { reject(e) }
})

function sendMessageToContentScript(message, callback) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    tabs[0] && chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
      if (callback) callback(response)
    })
  })
}


const main = async () => {

  chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
    sendResponse(true)
    try {
      const result = await translate(request)
      sendMessageToContentScript(JSON.stringify({ data: result, message: '' }))
    } catch (e) {
      sendMessageToContentScript(JSON.stringify({
        data: '',
        message: e.message
      }))
    }
  })

}

main()